package edu.wpi.cs509.network;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import edu.wpi.cs509.messages.MsgBc;

/**
 * Encapsulates a connection between the client and server.
 * 
 * @author mreiter
 * @author saerb
 * @author adveres
 * @author ldanxian
 */
public class Connection {
	/** The object that owns this connection. */
	private ConnectionOwner owner;
	
	/** The socket wrapped by this connection. */
	private Socket socket;
	
	/** The input stream used to receive messages from the remote host. */
	private ObjectInputStream input;
	
	/** The output stream used to send messages to the remote host. */
	private ObjectOutputStream output;
	
	/** The thread that listens for messages from the remote host. */
	private ConnectionThread connectionThread;
	
	/** Store the username in each connection. This is where we get he username for logout */
	private String username;

	/**
	 * Connects to the specified host.
	 * 
	 * @param owner The owner of this connection.
	 * @param hostname The name or IP address of the host.
	 * @throws UnknownHostException
	 * @throws IOException
	 */
	public Connection(ConnectionOwner owner, String hostname) throws UnknownHostException, IOException {
		this(owner, new Socket(hostname, ConnectionListener.SERVER_PORT));
	}
	
	/**
	 * Creates a connection for an existing socket.
	 * 
	 * @param owner The owner of this connection.
	 * @param socket The socket for this connection.
	 * @throws IOException 
	 */
	Connection(ConnectionOwner owner, Socket socket) throws IOException {
		System.out.println("Connection opened to " + socket.getInetAddress());
		
		this.owner = owner;
		this.socket = socket;
		this.output = new ObjectOutputStream(socket.getOutputStream());
		this.input = new ObjectInputStream(socket.getInputStream());
		
		// Create a new thread to listen for messages from the remote host
		connectionThread = new ConnectionThread();
		connectionThread.setDaemon(true);
		connectionThread.start();
	}
	
	/**
	 * Closes the connection.
	 */
	public synchronized void close() {
		try {
			socket.close();
		} catch (IOException e) {}
	}
	
	/**
	 * @return The object that owns this connection.
	 */
	public Object getOwner() {
		return owner;
	}

	public void setUser(String username) {
		this.username = username;
	}
	
	/**
	 * 
	 * @return the user name associated with this connection
	 */
	public String getUser() {
		return username;
	}
	
	/**
	 * Sends a message to the remote host.
	 * 
	 * @param message The message to send.
	 * @throws IOException 
	 */
	public synchronized void sendMessage(MsgBc message) {
		// Only send the message of the socket has not been closed. If it has,
		// we assume that the connection thread will notify that connection owner
		// that the connection has been closed.
		if (!socket.isClosed()) {
			try {
				output.writeObject(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			System.err.println("Attempting to send message [" + message.toString() + "] to a closed socket.");
		}
	}
	
	/**
	 * Creates and returns a String representing this Connection object.
	 * 
	 * @return connectionString The string containing data about this connection.
	 */
	@Override
	public String toString()
	{
		String connectionString = "[Connection "+super.toString()+"] has owner ["+this.owner+"] and "+ this.socket;
		
		return connectionString;
	}
	
	/**
	 * Called if the connection is closed to signal the client/server to clean up.
	 */
	private void handleDisconnect()
	{
		if (socket.isClosed())
		{
			System.out.println("Connection closed by local host");
		}
		else
		{
			System.out.println("Connection closed by remote host");
			owner.handleDisconnect(Connection.this);
		}
	}
	
	/**
	 * A thread that listens for messages from the remote host.
	 */
	private class ConnectionThread extends Thread {
		/**
		 * Listens for messages from the remote host.
		 */
		@Override
		public void run() {
			try {
				// Keep reading objects until the connection is closed
				while (!socket.isClosed()) {
					// Read in an object and process it if it is of the correct type
					Object obj = input.readObject();
					if (obj instanceof MsgBc) {
						try {
							// Set the connection and execute the message handler
							MsgBc message = (MsgBc)obj;
							message.setConnection(Connection.this);
							message.rxExecute();
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else if (obj != null) {
						System.err.println("Received a message of an invalid type: " + obj.getClass());
					}
				}
			} catch (SocketException e) { // The connection was closed
				handleDisconnect();
			} catch (EOFException e) { // The connection was closed
				handleDisconnect();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// If we got out of the loop, close the connection
				close();
			}
		}
	}
}
